package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.FriendApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加好友
     * @param userId
     * @param friendId
     */
    @Override
    public void save(Long userId, Integer friendId) {
        //1. 查询这两人本身是不是好友，如果不是好友，我们才新增数据
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if(!mongoTemplate.exists(query, Friend.class)){
        //新增为好友
            Friend friend  = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId.longValue());
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);

        }


        query = new Query(Criteria.where("friendId").is(userId).and("userId").is(friendId));
        if(!mongoTemplate.exists(query, Friend.class)){
            //新增为好友
            Friend friend  = new Friend();
            friend.setUserId(friendId.longValue());
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(friend);
        }

    }

    @Override
    public PageResult findFriendByUserId(Long userId, Integer page, Integer pagesize) {
        //如果搜索的关键字为空，则不需要管理
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        Long count = mongoTemplate.count(query, Friend.class);
        PageResult pageResult = new PageResult(page,pagesize,count.intValue(),friendList);
        return pageResult;
    }
}
